package com.example.easybuy.controller;

import com.example.easybuy.entity.User;
import com.example.easybuy.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/api/users")
public class UserController {
    
    @Autowired
    private UserService userService;
    
    /**
     * 创建用户索引
     *
     * @return 是否创建成功
     * @throws IOException IO异常
     */
    @PostMapping("/index")
    public boolean createIndex() throws IOException {
        return userService.createIndex();
    }
    
    /**
     * 保存用户
     *
     * @param user 用户对象
     * @return 文档ID
     * @throws IOException IO异常
     */
    @PostMapping
    public String save(@RequestBody User user) throws IOException {
        return userService.save(user);
    }
    
    /**
     * 根据ID获取用户
     *
     * @param id 用户ID
     * @return 用户对象
     * @throws IOException IO异常
     */
    @GetMapping("/{id}")
    public User getById(@PathVariable Long id) throws IOException {
        return userService.getById(id);
    }
    
    /**
     * 更新用户信息
     *
     * @param id   用户ID
     * @param user 用户对象
     * @return 是否更新成功
     * @throws IOException IO异常
     */
    @PutMapping("/{id}")
    public boolean update(@PathVariable Long id, @RequestBody User user) throws IOException {
        user.setId(id);
        return userService.update(user);
    }
    
    /**
     * 根据ID删除用户
     *
     * @param id 用户ID
     * @return 是否删除成功
     * @throws IOException IO异常
     */
    @DeleteMapping("/{id}")
    public boolean deleteById(@PathVariable Long id) throws IOException {
        return userService.deleteById(id);
    }
    
    /**
     * 获取所有用户
     *
     * @return 用户列表
     * @throws IOException IO异常
     */
    @GetMapping
    public List<User> getAllUsers() throws IOException {
        return userService.getAllUsers();
    }
}